package com.iwuyc.fastexcel.ext.util

class ExcelUtils {
    companion object {
        private const val A_UPPERCASE_CHAR = 'A'
        private const val RADIX_26 = 26
        @JvmStatic
        fun rowIndexToAlpha(columnIndex: Int): String {
            var columnIndex = columnIndex
            require(columnIndex > 0) { "输入必须是正整数" }

            val resultBuilder = StringBuilder()

            while (columnIndex > 0) {
                // 由于是1-26对应A-Z，先将num减1，转为0-25的范围
                columnIndex--
                // 取当前位对应的字符（0->A，1->B，...，25->Z）
                val c = (A_UPPERCASE_CHAR + columnIndex % RADIX_26)
                // 将字符插入到结果的最前面（因为是从低位到高位计算）
                resultBuilder.insert(0, c)
                // 计算下一位（相当于除以26）
                columnIndex = columnIndex / RADIX_26
            }

            return resultBuilder.toString()
        }
        
        @JvmStatic
        fun alphaToRowIndex(rowAlpha: String): Int {
            require(rowAlpha.isNotEmpty()) { "输入不能为空" }
            val rowAlpha = rowAlpha.uppercase()
            var result = 0
            for (char in rowAlpha) {
                require(char.isLetter()) { "输入只能包含字母" }
                result = result * RADIX_26 + (char - A_UPPERCASE_CHAR + 1)
            }
            
            return result
        }
    }

    
}